#include "molecular_core.h"

namespace M {
Core::Core()
{

}

Core::~Core()
{

}

bool
Core::AddMCA(Atom *pAtom)
{
    if(NULL == pAtom) {
        return false;
    }

    String strAtomName = pAtom->name();
    AtomList::iterator oAtomIt = m_vAtoms.find(strAtomName);
    if(oAtomIt != m_vAtoms.end()) {
        return false;
    }

    pAtom->Init(this);

    m_vAtoms[strAtomName] = pAtom;

    return true;
}

bool
Core::RemoveMCA(Atom *pAtom)
{
    if(NULL == pAtom) {
        return false;
    }

    String strAtomName = pAtom->name();
    AtomList::iterator oAtomIt = m_vAtoms.find(strAtomName);
    if(oAtomIt == m_vAtoms.end()) {
        return false;
    }

    if(oAtomIt->second != pAtom) {
        return false;
    }

    m_vAtoms.erase(oAtomIt);
    pAtom->Uninit();

    return true;
}

Atom *
Core::GetAtom(const String &strAtomId)
{
    AtomList::iterator oAtomIt = m_vAtoms.find(strAtomId);
    if(oAtomIt == m_vAtoms.end()) {
        return NULL;
    }

    return oAtomIt->second;
}

bool
Core::Execute(const String &strAtomId, int nFuncId, void *pParams, void *pIOParams)
{
    return Execute(AtomEndPoint(), strAtomId, nFuncId, pParams, pIOParams);
}

bool
Core::Execute(const AtomEndPoint &oSrcAtom, const String &strAtomId, int nFuncId, void *pParams, void *pIOParams)
{
    AtomList::iterator oAtomIt = m_vAtoms.find(strAtomId);
    if(oAtomIt == m_vAtoms.end()) {
        return false;
    }

    return oAtomIt->second->OnExecute(oSrcAtom, nFuncId, pParams, pIOParams);
}

bool
Core::FireEvent(int nEventId, void *pParams)
{
    return FireEvent(AtomEndPoint(), nEventId, pParams);
}

bool
Core::FireEvent(const AtomEndPoint &oSrcAtom, int nEventId, void *pParams)
{
    AtomList::iterator oAtomIt = m_vAtoms.begin();
    while(oAtomIt != m_vAtoms.end()) {
        oAtomIt->second->OnEvent(oSrcAtom, nEventId, pParams);
        ++oAtomIt;
    }

    return true;
}
}